/**
  ******************************************************************************
  * @file           : delay.c
  * @author			: duanzhe
  * @brief          : 阻塞式延时函数，us级和ms级
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 乐普医电.
  *
  ******************************************************************************
  */
#include "delay.h"

/**
  * @brief   us延时，通过持续读取SysTick定时器的计数值来估算延时时间
  * @param   要延时的us数
  * @retval  无
  */
void delay_us(uint16_t num)
{
    uint32_t local_cnt = 0;
    uint32_t systick_load;
    uint32_t prev_tick;
    uint32_t now_tick;
    uint32_t des_tick;

    des_tick = num * (SystemCoreClock / (1000 * 1000));
    systick_load = SysTick->LOAD;
    prev_tick = SysTick->VAL;
    while (1)
    {
        now_tick = SysTick->VAL;
        if (now_tick != prev_tick) {
            if (now_tick < prev_tick) {
                local_cnt += prev_tick - now_tick;
            }
            else {
                local_cnt += systick_load - now_tick + prev_tick;
            }
            prev_tick = now_tick;
            if (local_cnt >= des_tick) {
                break;
            }
        }
    }
}

/**
  * @brief   ms延时，持续调用us级延时函数，延时多个ms
  * @param   要延时的ms数
  * @retval  无
  */
void delay_ms(uint16_t num)
{
    for (; num > 0; num--)
    {
        delay_us(1000);
    }
}
